import GroupModel from '../model/groupModel.js';
import Result from '../common/result.js';
import { getTokenInfo } from '../common/auth.js';

const GroupController = {
  // Get group list
  async getList(req, res) {
    try {
      if (!req.params.page || isNaN(req.params.page)) {
        req.params.page = 1;
      }
      // Add current user ID to query parameters
      const studentId = getTokenInfo(req.headers.authorization).id;
      req.query.studentId = studentId;

      const groups = await GroupModel.getList(req.query, req.params.page);
      return Result.success(res, groups);
    } catch (error) {
      console.error('Get group list error:', error);
      return Result.error(res, 'Failed to get group list');
    }
  },

  // Get group details
  async getById(req, res) {
    const { id } = req.params;
    if (!id) {
      return Result.badRequest(res);
    }
    const group = await GroupModel.getById(id);
    const members = await GroupModel.getMembers(id);
    if (!group) {
      return Result.notFound(res, 'Group not found');
    }
    if (members && members.length > 0) {
      group.Members = members;
    } else {
      group.Members = [];
    }
    return Result.success(res, group);
  },

  // Create group
  async create(req, res) {
    const { name, description, type, privacy } = req.body;
    if (!name || !description || !type || !privacy) {
      return Result.badRequest(res, 'Missing required fields');
    }
    const adminId = getTokenInfo(req.headers.authorization).id;
    const group = { name, description, type, privacy, adminId };
    const result = await GroupModel.insert(group);
    return Result.success(res, result);
  },

  // Update group
  async update(req, res) {
    const { id } = req.params;
    const { name, description, type, privacy } = req.body;
    if (!name || !description || !type || !privacy) {
      return Result.badRequest(res);
    }
    
    const group = await GroupModel.getById(id);
    if (!group) {
      return Result.notFound(res, 'Group not found');
    }
    
    const adminId = getTokenInfo(req.headers.authorization).id;
    if (adminId !== group.AdminID) {
      return Result.error(res, 'Not authorized to update this group', Result.ACCESS_DENIED_CODE);
    }
    
    const updatedGroup = { name, description, type, privacy };
    const result = await GroupModel.update(id, updatedGroup);
    return Result.success(res, result);
  },

  // Delete group
  async delete(req, res) {
    const { id } = req.params;
    const group = await GroupModel.getById(id);
    if (!group) {
      return Result.notFound(res, 'Group not found');
    }
    
    const adminId = getTokenInfo(req.headers.authorization).id;
    if (adminId !== group.AdminID) {
      return Result.error(res, 'Not authorized to delete this group', Result.BAD_REQUEST_CODE);
    }
    
    const result = await GroupModel.delete(id);
    return Result.success(res, result);
  },

  // Join group
  async join(req, res) {
    const { id } = req.params;
    const studentId = getTokenInfo(req.headers.authorization).id;
    
    const isMember = await GroupModel.isMember(id, studentId);
    if (isMember) {
      return Result.error(res, 'Already a member of this group');
    }
    
    const result = await GroupModel.joinGroup(id, studentId);
    return Result.success(res, result);
  },

  // Leave group
  async leave(req, res) {
    const { id } = req.params;
    const studentId = getTokenInfo(req.headers.authorization).id;
    
    const isMember = await GroupModel.isMember(id, studentId);
    if (!isMember) {
      return Result.error(res, 'Not a member of this group');
    }
    
    const result = await GroupModel.leaveGroup(id, studentId);
    return Result.success(res, result);
  },

  // Leave group method
  async leaveGroup(req, res) {
    const { id } = req.params;
    const studentId = getTokenInfo(req.headers.authorization).id;
    
    try {
      await GroupModel.leaveGroup(id, studentId);
      return Result.success(res, null, 'Left group successfully');
    } catch (error) {
      return Result.error(res, 'Failed to leave group');
    }
  }
};

export default GroupController;